package 算法.leetcode.linked.list;

import org.junit.Test;

/**
 * @author lchenglong
 * @date 2020/12/24
 */
public class MergeTwoLists extends LinkListBase {

    @Test
    public void test() {
        int[] arr1 = new int[]{1, 3, 5, 7, 9};
        int[] arr2 = new int[]{2, 4, 6, 8, 10};
        ListNode res = mergeTwoLists(createTestData(arr1), createTestData(arr2));
        toString(res);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null;
        if (l1 == null && l2 == null) return null;
        if (l1 == null) {
            head = l2;
            l2 = l2.next;
        } else {
            if (l2 == null) {
                head = l1;
                l1 = l1.next;
            } else if (l1.val <= l2.val) {
                head = l1;
                l1 = l1.next;
            } else {
                head = l2;
                l2 = l2.next;
            }
        }
        ListNode cur = head;

        while (l1 != null || l2 != null) {
            if (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    cur.next = l1;
                    cur = cur.next;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    cur = cur.next;
                    l2 = l2.next;
                }
            } else if (l1 != null) {
                cur.next = l1;
                cur = cur.next;
                l1 = l1.next;
            } else {
                cur.next = l2;
                cur = cur.next;
                l2 = l2.next;
            }
        }
        return head;
    }
}
